package com.davidk.survey.server.user;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.davidk.survey.server.DataRequest;
import com.davidk.survey.server.model.smartgwtrest.ErrorResponse;
import com.davidk.survey.server.model.smartgwtrest.Response;

@Controller
@RequestMapping("/users")
public class UserController {

	private static UserDAO ds = new UserDAO();

	@ModelAttribute("response")
	@RequestMapping(value = "save", method = RequestMethod.POST)
	public Response addApi(@RequestBody UserSaveRequest reqBody, HttpServletRequest request) throws IOException {
		try {
			if (reqBody.getOperationType().equals("fetch"))
				return ds.fetch(reqBody);
			if (reqBody.getOperationType().equals("add"))
				return ds.add(reqBody, reqBody.getData());
			if (reqBody.getOperationType().equals("update"))
				return ds.update(reqBody, reqBody.getData());
			if (reqBody.getOperationType().equals("remove"))
				return ds.remove(reqBody, reqBody.getData());
			return new ErrorResponse(Response.STATUS_FAILURE, "Controller : Unable to execute operation : "
					+ reqBody.getOperationType());
		} catch (Exception ex) {
			return new ErrorResponse(Response.STATUS_FAILURE, "Controller : Unknown Error : " + ex.getMessage());
		}
	}
	
	@ModelAttribute("response")
	@RequestMapping(value = "fetch", method = RequestMethod.GET)
	public Response baseApi(HttpServletRequest request) throws IOException {
		try {
			DataRequest req = DataRequest.from(request);
			if (req.getOperationType().equals("fetch"))
				return ds.fetch(req);
			return new ErrorResponse(Response.STATUS_FAILURE, "Controller : Unable to execute operation : "
					+ req.getOperationType());
		} catch (Exception ex) {
			return new ErrorResponse(Response.STATUS_FAILURE, "Controller : Unknown Error : " + ex.getMessage());
		}

	}

}
